//
//  QuestionPublicViewController.m
//  zhijian
//
//  Created by lcb on 2019/1/20.
//  Copyright © 2019 lcb. All rights reserved.
//

#import "QuestionPublicViewController.h"
#import "Base.h"
#import "LTPlaceholderTextView.h"
#import "PhotoGridView.h"
#import <ZLPhotoBrowser/ZLPhotoBrowser.h>
#import "ZLCustomCamera.h"
@interface QuestionPublicViewController ()<UITextViewDelegate,PhotoGridViewDataSource, PhotoGridViewDelegate>
{

}
@property (nonatomic, strong) UIView * publicView;
@property (nonatomic, strong) LTPlaceholderTextView * textView;
//字数的限制
@property (nonatomic, strong)UILabel *wordCountLabel;
@property (nonatomic, strong)PhotoGridViewFlowLayout *gridViewFlowLayout;
@property (nonatomic, strong)PhotoGridView *gridView;
@property (nonatomic, strong) NSMutableArray<UIImage *> *selectedPhotos;
@property (nonatomic, strong) NSMutableArray<PHAsset *> *selectedAssets;
@property (nonatomic, assign) CGFloat isSelectOriginalPhoto;
@property (nonatomic, assign) CGFloat itemWH;
@property (nonatomic, assign) CGFloat margin;
@end

@implementation QuestionPublicViewController
@synthesize questionModel=_questionModel;
@synthesize type=_type;

- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *titlestr =@"发表评论";
    if ([_type isEqualToString:@"questions"])
    {
        titlestr =@"我要咨询";
    }
    [self hyb_navWithLeftImage:@"back" title:titlestr rightTitle:@"发布" leftClicked:^(UIButton *sender) {
        [self.navigationController popViewControllerAnimated:YES];
    } rightClicked:^(UIButton *sender) {
        [self sendFeedBack];
    }];
    // Do any additional setup after loading the view.
    if (!_selectedPhotos) {
        _selectedPhotos = [NSMutableArray array];
    }
    if (!_selectedAssets) {
        _selectedAssets = [NSMutableArray array];
    }
    [self initUI];
}

-(void)initUI
{
    self.publicView = [[UIView alloc]init];
    _publicView.backgroundColor = [UIColor whiteColor];
    _publicView.frame = CGRectMake(10, 84+[BaseShare statusBarHeight], SCREEN_WIDTH- 20, 110);
    [self.view addSubview:_publicView];
    //
    self.textView.frame =CGRectMake(0, 0, _publicView.frame.size.width, 100);
    [_publicView addSubview:self.textView];
    //
    self.wordCountLabel = [[UILabel alloc]initWithFrame:CGRectMake(_publicView.frame.size.width-75,  self.textView.frame.size.height -22, 70, 20)];
    _wordCountLabel.font = [UIFont systemFontOfSize:14.f];
    _wordCountLabel.textColor = [UIColor lightGrayColor];
    self.wordCountLabel.text = @"0/300";
    self.wordCountLabel.backgroundColor = [UIColor whiteColor];
    self.wordCountLabel.textAlignment = NSTextAlignmentRight;
    [_publicView addSubview:_wordCountLabel];
    //
    //
    CGFloat y =self.publicView.frame.origin.y + self.publicView.frame.size.height +10;
    self.gridView.frame = CGRectMake(0,y, SCREEN_WIDTH, SCREEN_WIDTH);
    [self.view addSubview:self.gridView];
}
-(LTPlaceholderTextView *)textView{
    
    if (!_textView) {
        _textView = [[LTPlaceholderTextView alloc]initWithFrame:CGRectZero];
        _textView.backgroundColor = [UIColor whiteColor];
        _textView.delegate = self;
        _textView.font = [UIFont systemFontOfSize:14.f];
        _textView.textColor = [UIColor blackColor];
        _textView.textAlignment = NSTextAlignmentLeft;
        _textView.editable = YES;
        _textView.layer.cornerRadius = 4.0f;
        _textView.layer.borderColor = [UIColor grayColor].CGColor;
        _textView.layer.borderWidth = 0.5;
        _textView.placeholder = @"写下你遇到的问题~";
        _textView.textLimitType =LTTextLimitTypeLength;
        _textView.textLimitSize=300;
        _textView.maxSize =300;
    }
    
    return _textView;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [_textView resignFirstResponder];
}

//在这个地方计算输入的字数
- (void)textViewDidChange:(UITextView *)textView
{
    NSInteger wordCount = textView.text.length;
    self.wordCountLabel.text = [NSString stringWithFormat:@"%ld/300",(long)wordCount];
}
#pragma mark - PhotoGridView
-(PhotoGridView*)gridView
{
    if (!_gridView) {
        _gridViewFlowLayout = [[PhotoGridViewFlowLayout alloc] init];
        self.margin = 4;
        self.itemWH =(SCREEN_WIDTH - 2 * self.margin - 4) / 4 - self.margin;
        _gridViewFlowLayout.itemSize = CGSizeMake(self.itemWH, self.itemWH);
        _gridViewFlowLayout.minimumInteritemSpacing = self.margin;
        _gridViewFlowLayout.minimumLineSpacing = self.margin;
        //
        _gridView = [[PhotoGridView alloc] initWithFrame:CGRectZero collectionViewLayout:_gridViewFlowLayout];
        _gridView.contentInset = UIEdgeInsetsMake(4, 4, 4, 4);
        _gridView.delegate = self;
        _gridView.dataSource = self;
        _gridView.scrollEnabled = NO;
        _gridView.backgroundColor = [UIColor whiteColor];
        [_gridView registerClass:[PhotoGridViewCell class] forCellWithReuseIdentifier:@"PhotoGridViewCellReuseIdentifier"];
    }
    return _gridView;
}

#pragma mark - delegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _selectedPhotos.count + 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    PhotoGridViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PhotoGridViewCellReuseIdentifier" forIndexPath:indexPath];
    cell.videoImageView.hidden = YES;
    if (indexPath.item == _selectedPhotos.count) {
        cell.imageView.image = [UIImage imageNamed:@"photos"];
        cell.deleteBtn.hidden = YES;
        cell.gifLable.hidden = YES;
    } else {
        cell.imageView.image = _selectedPhotos[indexPath.item];
        cell.asset = _selectedAssets[indexPath.item];
        cell.deleteBtn.hidden = NO;
    }
    cell.deleteBtn.tag = indexPath.item;
    [cell.deleteBtn addTarget:self action:@selector(deleteBtnClik:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.item == _selectedPhotos.count) {
    
        UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction *takePhotoAction = [UIAlertAction actionWithTitle: @"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self takePhoto];
        }];
        [alertVc addAction:takePhotoAction];
        UIAlertAction *imagePickerAction = [UIAlertAction actionWithTitle:@"去相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[self photoActionSheet] showPhotoLibrary];
        }];
        [alertVc addAction:imagePickerAction];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [alertVc addAction:cancelAction];
        UIPopoverPresentationController *popover = alertVc.popoverPresentationController;
        UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
        if (popover) {
            popover.sourceView = cell;
            popover.sourceRect = cell.bounds;
            popover.permittedArrowDirections = UIPopoverArrowDirectionAny;
        }
        [self presentViewController:alertVc animated:YES completion:nil];
    }else{
        [[self photoActionSheet] previewSelectedPhotos:self.selectedPhotos assets:self.selectedAssets index:indexPath.item isOriginal:self.isSelectOriginalPhoto];
    }
}
#pragma mark - Click Event

- (void)deleteBtnClik:(UIButton *)sender {
    if ([self collectionView:self.gridView numberOfItemsInSection:0] <= _selectedPhotos.count) {
        [_selectedPhotos removeObjectAtIndex:sender.tag];
        [_selectedAssets removeObjectAtIndex:sender.tag];
        [self.gridView reloadData];
        return;
    }
    [_selectedPhotos removeObjectAtIndex:sender.tag];
    [_selectedAssets removeObjectAtIndex:sender.tag];
    [_gridView performBatchUpdates:^{
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:sender.tag inSection:0];
        [self->_gridView deleteItemsAtIndexPaths:@[indexPath]];
    } completion:^(BOOL finished) {
        [self->_gridView reloadData];
    }];
}
#pragma mark - PhotoGridViewDataSource
/// 以下三个方法为长按排序相关代码
- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath {
    return indexPath.item < _selectedPhotos.count;
}

- (BOOL)collectionView:(UICollectionView *)collectionView itemAtIndexPath:(NSIndexPath *)sourceIndexPath canMoveToIndexPath:(NSIndexPath *)destinationIndexPath {
    return (sourceIndexPath.item < _selectedPhotos.count && destinationIndexPath.item < _selectedPhotos.count);
}

- (void)collectionView:(UICollectionView *)collectionView itemAtIndexPath:(NSIndexPath *)sourceIndexPath didMoveToIndexPath:(NSIndexPath *)destinationIndexPath {
    UIImage *image = _selectedPhotos[sourceIndexPath.item];
    [_selectedPhotos removeObjectAtIndex:sourceIndexPath.item];
    [_selectedPhotos insertObject:image atIndex:destinationIndexPath.item];
    
    id asset = _selectedAssets[sourceIndexPath.item];
    [_selectedAssets removeObjectAtIndex:sourceIndexPath.item];
    [_selectedAssets insertObject:asset atIndex:destinationIndexPath.item];
    
    [_gridView reloadData];
}
- (ZLPhotoActionSheet *)photoActionSheet
{
    ZLPhotoActionSheet *actionSheet = [[ZLPhotoActionSheet alloc] init];
    actionSheet.configuration.languageType = ZLLanguageChineseSimplified;
    actionSheet.configuration.navBarColor =navColor;
    //设置照片最大选择数
    actionSheet.configuration.maxSelectCount = 3;
    actionSheet.configuration.allowMixSelect =NO;
    actionSheet.configuration.allowSelectImage=YES;
    actionSheet.configuration.allowSelectVideo=NO;
    actionSheet.configuration.allowSelectGif=NO;
    //如果调用的方法没有传sender，则该属性必须提前赋值
    actionSheet.sender = self;
    actionSheet.arrSelectedAssets = self.selectedAssets;
    zl_weakify(self);
    [actionSheet setSelectImageBlock:^(NSArray<UIImage *> * _Nonnull images, NSArray<PHAsset *> * _Nonnull assets, BOOL isOriginal) {
        zl_strongify(weakSelf);
        strongSelf.selectedPhotos = [NSMutableArray arrayWithArray:images];
        strongSelf.selectedAssets = [NSMutableArray arrayWithArray:assets];
        strongSelf.isSelectOriginalPhoto = isOriginal;
        [strongSelf.gridView reloadData];
        strongSelf.gridView.contentSize = CGSizeMake(0, ((weakSelf.selectedPhotos.count + 2) / 3 ) * (weakSelf.margin + weakSelf.itemWH));
    }];
    actionSheet.cancleBlock = ^{
        NSLog(@"取消选择图片");
    };
    
    return actionSheet;
}
-(void)sendFeedBack
{
    if (self.textView.text.length==0) {
        [BaseToast showAtTop:@"请输入内容！"];
        return;
    }
    zl_weakify(self);
    if (self.selectedPhotos.count==0) {
        [self feed:@""];
    }else{
        [self uploadFile:^(ApiResponse * _Nonnull response, NSString * _Nonnull errorMsg) {
            if (response!=nil && response.code==0 ) {
                [weakSelf feed:response.data];
            }
        }];
    }
   
}
-(void)uploadFile:(callbackBlock)callback
{
    [[Api sharedApi] uploadImages:self.selectedPhotos callback:^(ApiResponse * _Nonnull response, NSString * _Nonnull errorMsg) {
        [BaseToast show:response.message];
        if (callback) {
            callback(response,errorMsg);
        }
    }];
}
-(void)feed:(NSString*)photos
{
    if (self.textView.text.length==0) {
        [BaseToast showAtTop:@"请输入内容！"];
        return;
    }
    zl_weakify(self);
    if ([self.type isEqualToString:@"questions"]) {
        [[Api sharedApi] publishQuestion:@"1" questionContent:self.textView.text questionPics:photos callback:^(ApiResponse * _Nonnull response, NSString * _Nonnull errorMsg) {
            weakSelf.textView.text=@"";
            [BaseToast show:response.message];
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }];
    }else{
        [[Api sharedApi] publishComment:[NSString stringWithFormat:@"%ld",self.questionModel.questionId] replyCommentId:@"" commentContent:weakSelf.textView.text commentPics:photos callback:^(ApiResponse * _Nonnull response, NSString * _Nonnull errorMsg) {
            weakSelf.textView.text=@"";
            [BaseToast show:response.message];
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }];
    }
}
-(void)takePhoto
{
    if (![ZLPhotoManager haveCameraAuthority]) {
        NSString *message = [NSString stringWithFormat:GetLocalLanguageTextValue(ZLPhotoBrowserNoCameraAuthorityText), kAPPName];
        [BaseToast show:message];
        return;
    }
    if (![ZLPhotoManager haveMicrophoneAuthority]) {
        NSString *message = [NSString stringWithFormat:GetLocalLanguageTextValue(ZLPhotoBrowserNoMicrophoneAuthorityText), kAPPName];
        [BaseToast show:message];
        return;
    }
    ZLCustomCamera *camera = [[ZLCustomCamera alloc] init];
    camera.allowTakePhoto = YES;
    camera.allowRecordVideo = NO;
    zl_weakify(self);
    camera.doneBlock = ^(UIImage *image, NSURL *videoUrl) {
        if (image) {
            [ZLPhotoManager saveImageToAblum:image completion:^(BOOL suc, PHAsset *asset) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (suc) {
                        [self.selectedPhotos addObject:image];
                        [self.selectedAssets addObject:asset];
                        self.isSelectOriginalPhoto = YES;
                        [self.gridView reloadData];
                        self.gridView.contentSize = CGSizeMake(0, ((self.selectedPhotos.count + 2) / 3 ) * (self.margin + self.itemWH));
                        
                    } else {
                        ZLLoggerDebug(@"图片保存失败");
                    }
                });
            }];
            
        }
    };
    [self presentViewController:camera animated:YES completion:nil];
}
@end
